package com.ma.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ma.gulimall.auth.feign.MemberFeignService;
import com.ma.gulimall.auth.vo.GiteeUser;
import com.ma.gulimall.auth.vo.SocialUser;
import com.ma.gulimall.constant.AuthServerConstant;
import com.ma.gulimall.utils.HttpUtils;
import com.ma.gulimall.utils.R;
import com.ma.gulimall.vo.MemberResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName OAuth2Controller
 * @Author: mayongqiang
 * @DATE 2021/10/17 13:10
 * @Description: 社交登录
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {


        /**
         *  点击按钮 , 登录 ,获得code
         *  1、跳转至https://gitee.com/oauth/authorize?
         *          client_id=26aea2d0a1e5deb2d88f7701816185913acf76f119bf3bbd333d3b25c293055b
         *          &redirect_uri=http%3A%2F%2Fgulimall.com%2Foauth2.0%2Fgitee%2Fsuccess
         *          &response_type=code
         *  2、跳转至gitee登录   https://gitee.com/login?
         *          redirect_to_url=http%3A%2F%2Fgitee.com%2Foauth%2Fauthorize%3F
         *          client_id%3D26aea2d0a1e5deb2d88f7701816185913acf76f119bf3bbd333d3b25c293055b%26
         *          redirect_uri%3Dhttp%253A%252F%252Fgulimall.com%252Foauth2.0%252Fgitee%252Fsuccess%26
         *          response_type%3Dcode
         *
         *  3、用户登录，跳转至 http://gulimall.com/oauth2.0/gitee/success?
         *                  code=1fd4be4ea06bb75edfdee4c8b5ece6d0fe55c2cf796631cd387187552bdedba1
         * */
        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "authorization_code");
        map.put("client_id", "26aea2d0a1e5deb2d88f7701816185913acf76f119bf3bbd333d3b25c293055b");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("client_secret", "105ae6ded66ff88d5960bd45063914c5b58a8b3beb992c7b119ccf1575ce6368");
        map.put("code", code);

        //1、根据code换取access_token
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map, new HashMap<>());

        //2、处理
        if (response.getStatusLine().getStatusCode() == 200) {

            //成功则获取到access_token，取出来
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            System.out.println("登录后用code换取的token：" + socialUser.getAccess_token());

            //通过access_token,回调gitee/api/v5/user拿到uid,封装到socialUser中
            Map<String, String> map1 = new HashMap<>();
            map1.put("access_token", socialUser.getAccess_token());
            HttpResponse response1 = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), map1);
            String json1 = EntityUtils.toString(response1.getEntity());
            GiteeUser giteeUser = JSON.parseObject(json1, GiteeUser.class);
            socialUser.setUid(String.valueOf(giteeUser.getId()));
            //通过uid来判断用户是否登陆过
            //1、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个账户就对应指定的会员）


            //登录或者注册这个社交帐户----->调用远程服务
            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            if (oauthLogin.getCode() == 0) {
                //登录成功
                MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {
                });

                log.info("登陆成功：用户信息：\n{}", data.toString());
                //1、第一次使用session，命令浏览器保存卡号  JSESSIONID这个cookie
                //以后浏览器访问那个网站就会带上这个网站的cookies
                // TODO: 2021/10/17 1、默认的令牌当前域（—解决子域session共享的问题）
                // TODO: 2021/10/17 2、使用JSON序列化的方式将序列化对象到redis中

                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }


    }

}
